<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    // 1 使用set去重
    // let arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
    // let arr2 = new Set([...arr])
    // let arr3 = Array.from(arr2)
    // console.log('arr2==', arr2, Array.isArray(arr2))
    // console.log('arr3==', arr3, Array.isArray(arr3))

    // 2 使用双重for循环去重
    // let arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
    // let handleRemoveRepeat2 = (arr) => {
    //   let len = arr.length
    //   for (let i = 0; i < len; i++) {
    //     for (let j = i + 1; j < len; j++) {
    //       if (arr[i] === arr[j]) {
    //         arr.splice(j, 1)
    //         j--
    //         len--
    //       }
    //     }
    //   }
    //   return arr
    // }
    // console.log('去重后的数组为==', handleRemoveRepeat2(arr))

    // 3使用indexOf去重
    let arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 6, 0]
    // let handleRemoveRepeat3 = (arr) => {
    //   let len = arr.length
    //   let newArr = []
    //   for (let i = 0; i < len; i++) {
    //     if (newArr.indexOf(arr[i]) === -1) newArr.push(arr[i])
    //   }
    //   return newArr
    // }
    // console.log('333去重后的数组为==', handleRemoveRepeat3(arr))

    // 4使用filter去重
    // let handleRemoveRepeat4 = (arr) => {
    //   return arr.filter((item, index) => arr.indexOf(item) === index)
    // }
    // console.log('444去重后的数组为==', handleRemoveRepeat4(arr))

    // 5使用reduce试试
    let handleRemoveRepeat5 = (arr, name) => {
      let hash = {}
      return arr.reduce((pre, cur, index, arrs) => {
        let key = name ? cur[name] : cur
        hash[key] ? '' : (hash[key] = true && pre.push(cur))
        return pre
      }, [])
    }
    let arrObj = [
      { id: 1, name: 'aa' },
      { id: 2, name: 'bb' },
      { id: 2, name: 'cc' },
      { id: 1, name: 'dd' },
    ]
    console.log('555去重后的数组为==', handleRemoveRepeat5(arrObj, 'id'))
  </script>
</html>
